<!--
 - Author : chenyliu.
 - Date   : 2016/9/9.
 - File   : wh-brand.vue.
 -->

<template>
  <div>
    <div class="pull-right">
      <button class="btn btn-primary btn-sm pull-left del-under btn-interval" @click="showAddBuildModal">
        <i class="glyphicon glyphicon-plus "></i>
        添加楼栋
      </button>
      <button class="btn btn-primary btn-sm pull-left del-under btn-interval" @click="showAddUnitModal">
        <i class="glyphicon glyphicon-plus "></i>
        添加单元
      </button>
      <button class="btn btn-primary btn-sm pull-left del-under btn-interval" @click="showAddHouseModal">
        <i class="glyphicon glyphicon-plus "></i>
        添加住宅
      </button>
    </div>
    <v-modal title="添加楼栋" :visible="addBuildEdit.show" :on-ok="addBuild"
             :on-cancel="hideAddBuildModal" :has-footer="false">
      <validator name="v1">
        <div class="page page-steps">
          <ul class="steps">
            <li :class="{'active': addBuildEdit.step==1}">
              <span class="circle">1</span>
              <span class="title">楼栋编号</span>
            </li>
            <li :class="{'active': addBuildEdit.step==2}">
              <span class="circle">2</span>
              <span class="title">设置单元</span>
            </li>
            <li :class="{'active': addBuildEdit.step==3}">
              <span class="circle">3</span>
              <span class="title">设置住宅</span>
            </li>
          </ul>
          <div class="step-module" v-show="addBuildEdit.step==1">
            <div class="form-horizontal">
              <div class="form-group">
                <label for="inputaccountUpdate" class="col-xs-2 control-label account">楼栋编号</label>
                <div class="col-xs-3">
                  <input v-el:buildnum-edit type="number" class="form-control" v-model="addBuildEdit.buildNum"
                         placeholder="" v-validate:buildnum="{required: true,min:1}">
                </div>
              </div>
              <div class="form-group">
                <div class="col-xs-offset-9 col-xs-2">
                  <button class="btn btn-primary" @click="addBuildNextStep1Click">下一步</button>
                </div>
              </div>
            </div>
          </div>
          <div class="step-module" v-show="addBuildEdit.step==2">
            <div class="form-horizontal">
              <div class="form-group">
                <label class="col-xs-2 control-label" style="font-size:14px">单元数</label>
                <div class="col-xs-3">
                  <input type="number" class="form-control" v-model="addBuildEdit.unitCount" placeholder=""
                         v-validate:unitnum="{required:true,min:1}">
                </div>
              </div>
              <div class="form-group">
                <div class="col-xs-offset-9 col-xs-2">
                  <button class="btn btn-primary" @click="addBuildNextStep2Click">下一步</button>
                </div>
              </div>
            </div>
          </div>
          <div class="step-module" v-show="addBuildEdit.step==3">
            <div class="form-horizontal">
              <table class="table table-striped table-hover">
                <thead>
                <tr>
                  <th>单元编号</th>
                  <th>开始/结束楼层</th>
                  <th>开始/结束房号</th>
                </tr>
                </thead>
                <tbody>
                <tr v-for="unit in addBuildEdit.unitList">
                  <td>
                    <div class="unit-name">
                      <label type="control-label col-xs-2">{{unit.unitName}}</label>
                    </div>
                  </td>
                  <td>
                    <div class="num-group">
                      <input type="number" class="num-input" v-model="unit.beginFloor" :field="'beginfloor'+$index"
                             v-validate="{required:true,min:1}">
                      <label class="begin-end">~</label>
                      <input type="number" class="num-input" v-model="unit.endFloor" :field="'endfloor'+$index"
                             v-validate="{required:true,min:unit.beginFloor}">
                    </div>
                  </td>
                  <td>
                    <div class="num-group">
                      <input type="number" class="num-input" v-model="unit.beginHouseNum"
                             :field="'beginhousenum'+$index" v-validate="{required:true}">
                      <label class="begin-end">~</label>
                      <input type="number" class="num-input" v-model="unit.endHouseNum" :field="'endhousenum'+$index"
                             v-validate="{required:true}">
                    </div>
                  </td>
                </tr>
                </tbody>
              </table>
              <div class="form-horizontal">
                <div class="form-group">
                  <div class="col-xs-offset-9 col-xs-2">
                    <button class="btn btn-primary" @click="addBuildOkClick">保存</button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </validator>
    </v-modal>
    <v-modal title="添加单元" :visible="addUnitEdit.show" :on-ok="addBuild"
             :on-cancel="hideAddUnitModal" :has-footer="false">
      <validator name="v2">
        <div class="page page-steps">
          <ul class="steps">
            <li :class="{'active': addUnitEdit.step==1}">
              <span class="circle">1</span>
              <span class="title">添加单元</span>
            </li>
            <li :class="{'active': addUnitEdit.step==2}">
              <span class="circle">2</span>
              <span class="title">设置住宅</span>
            </li>
          </ul>
          <div class="step-module" v-show="addUnitEdit.step==1">
            <div class="form-horizontal">
              <div class="form-group">
                <label for="inputaccountUpdate" class="col-xs-2 control-label account">楼栋</label>
                <div class="col-xs-3">
                  <select class="form-control form-control-huy" v-model="addUnitEdit.buildId"
                          v-validate:buildid="{required:true}">
                    <option v-for="build in buildList" :value="build.buildingId">{{build.buildingName}}</option>
                  </select>
                </div>
              </div>
            </div>
            <div class="form-horizontal">
              <div class="form-group">
                <label for="inputaccountUpdate" class="col-xs-2 control-label" style="font-size:14px">单元编号</label>
                <div class="col-xs-3">
                  <input type="number" class="form-control" v-model="addUnitEdit.unitName" placeholder=""
                         v-validate:unitnum="{required:true,min:1}">
                </div>
              </div>
            </div>
            <div class="form-horizontal">
              <div class="form-group">
                <div class="col-xs-offset-9 col-xs-2">
                  <button class="btn btn-primary" @click="addUnitNextStep1Click">下一步</button>
                </div>
              </div>
            </div>
          </div>
          <div class="step-module" v-show="addUnitEdit.step==2">
            <div class="form-horizontal">
              <table class="table table-striped table-hover">
                <thead>
                <tr>
                  <th>单元编号</th>
                  <th>开始/结束楼层</th>
                  <th>开始/结束房号</th>
                </tr>
                </thead>
                <tbody>
                <tr v-for="unit in addUnitEdit.unitList">
                  <td>
                    <div class="unit-name">
                      <label type="control-label col-xs-2">{{unit.unitName}}</label>
                    </div>
                  </td>
                  <td>
                    <div class="num-group">
                      <input type="number" class="num-input" v-model="unit.beginFloor" :field="'beginfloor'+$index"
                             v-validate="{required:true,min:1}">
                      <label class="begin-end">~</label>
                      <input type="number" class="num-input" v-model="unit.endFloor" :field="'endfloor'+$index"
                             v-validate="{required:true,min:unit.beginFloor}">
                    </div>
                  </td>
                  <td>
                    <div class="num-group">
                      <input type="number" class="num-input" v-model="unit.beginHouseNum"
                             :field="'beginhousenum'+$index" v-validate="{required:true}">
                      <label class="begin-end">~</label>
                      <input type="number" class="num-input" v-model="unit.endHouseNum" :field="'endhousenum'+$index"
                             v-validate="{required:true}">
                    </div>
                  </td>
                </tr>
                </tbody>
              </table>
              <div class="form-horizontal">
                <div class="form-group">
                  <div class="col-xs-offset-9 col-xs-2">
                    <button class="btn btn-primary" @click="addUnitOkClick">保存</button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </validator>
    </v-modal>
    <v-modal title="添加住宅" :visible="addHouseEdit.show"
             :on-cancel="hideAddHouseModal" :has-footer="false">
      <validator name="v3">
        <div class="page page-steps">
          <div class="form-horizontal">
            <div class="form-group">
              <label for="inputaccountUpdate" class="col-xs-2 control-label account">楼栋</label>
              <div class="col-xs-3">
                <select class="form-control form-control-huy" v-model="addHouseEdit.buildId"
                        @change="addHouseBuildChange" v-validate:buildid="{required:true}">
                  <option v-for="build in buildList" :value="build.buildingId">{{build.buildingName}}</option>
                </select>
              </div>
            </div>
          </div>
          <div class="form-horizontal">
            <div class="form-group">
              <label for="inputaccountUpdate" class="col-xs-2 control-label" style="font-size:14px">单元</label>
              <div class="col-xs-3">
                <select class="form-control form-control-huy" v-model="addHouseEdit.unitId"
                        v-validate:unitid="{required:true}">
                  <option v-for="unit in addHouseEdit.unitList" :value="unit.unitId">{{unit.unitName}}({{unit.unitName}})
                  </option>
                </select>
              </div>
            </div>
          </div>
          <div class="form-horizontal">
            <table class="table table-striped table-hover">
              <thead>
              <tr>
                <th>开始/结束楼层</th>
                <th>开始/结束房号</th>
              </tr>
              </thead>
              <tbody>
              <tr>
                <td class="clear-td-first">
                  <div class="num-group">
                    <input type="number" class="num-input" v-model="addHouseEdit.beginFloor"
                           :field="'beginfloor'+$index" v-validate="{required:true,min:1}">
                    <label class="begin-end">~</label>
                    <input type="number" class="num-input" v-model="addHouseEdit.endFloor" :field="'endfloor'+$index"
                           v-validate="{required:true,min:addHouseEdit.beginFloor}">
                  </div>
                </td>
                <td>
                  <div class="num-group">
                    <input type="text" class="num-input" v-model="addHouseEdit.beginHouseNum"
                           :field="'beginhousenum'+$index" v-validate="{required:true}">
                    <label class="begin-end">~</label>
                    <input type="text" class="num-input" v-model="addHouseEdit.endHouseNum"
                           :field="'endhousenum'+$index" v-validate="{required:true}">
                  </div>
                </td>
              </tr>
              </tbody>
            </table>
            <div class="form-horizontal">
              <div class="form-group">
                <div class="col-xs-offset-9 col-xs-2">
                  <button class="btn btn-primary" @click="addHouseOkClick">保存</button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </validator>
    </v-modal>
  </div>
</template>

<script>
  import message from '../../components/message';
  import apiSource from '../../wohome-api'
  import {parseJSON, isSuccess} from '../../utils'
  import {clickElement, compress, isEmptyObject} from '../../utils/tool';
  import {createTab} from '../../vuex/action';
  import vModal from '../../components/modal';

  export default {
    props: {
      villageId: {
        type: String,
        default: ''
      },
      afterAddBuild: {
        type: Function,
        default: function () {

        }
      },
      afterAddUnit: {
        type: Function,
        default: function () {

        }
      },
      afterAddHouse: {
        type: Function,
        default: function () {

        }
      },
    },
    components: {
      vModal
    },
    data() {
      return {
        buildList: [],
        addBuildEdit: {show: false, step: 1, buildId: '', buildNum: '', unitCount: '', unitList: []},
        //unitList: [{unitName: '', beginFloor: '', endFloor: '', beginHouseNum: '', endHouseNum: ''},...]
        addUnitEdit: {show: false, step: 1, buildId: '', unitName: '', unitList: []},
        addHouseEdit: {
          show: false,
          buildId: '',
          unitList: [],
          unitId: '',
          beginFloor: '',
          endFloor: '',
          beginHouseNum: '',
          endHouseNum: ''
        },
      }
    },
    vuex: {
      getters: {}
    },
    ready() {
    },
    methods: {
      /**
       * 打开 添加楼栋 Modal
       */
      showAddBuildModal() {
        this.initBuildEdit();
        this.addBuildEdit.show = true;
        setTimeout(() => {
          this.$els.buildnumEdit.focus();
        }, 200)
      },
      /**
       * 关闭 添加楼栋 Modal
       */
      hideAddBuildModal() {
        this.addBuildEdit.show = false;
      },
      /**
       * 打开 添加单元 Modal
       */
      showAddUnitModal() {
        this.getBuildingList(this.villageId);
        this.initUnitEdit();
        this.addUnitEdit.show = true;
      },
      /**
       * 关闭 添加单元 Modal
       */
      hideAddUnitModal() {
        this.addUnitEdit.show = false;
      },
      /**
       * 打开 添加住宅 Modal
       */
      showAddHouseModal() {
        this.getBuildingList(this.villageId);
        this.initHouseEdit();
        this.addHouseEdit.show = true;
      },
      /**
       * 关闭 添加住宅 Modal
       */
      hideAddHouseModal() {
        this.addHouseEdit.show = false;
      },
      /**
       * 初始化 添加楼栋列表
       */
      initBuildEdit() {
        this.addBuildEdit.show = false;
        this.addBuildEdit.step = 1;
        this.addBuildEdit.buildId = '';
        this.addBuildEdit.buildNum = '';
        this.addBuildEdit.unitCount = '';
        this.addBuildEdit.unitList = [];
      },
      /**
       * 初始化 添加单元列表
       */
      initUnitEdit() {
        this.addUnitEdit.show = false;
        this.addUnitEdit.step = 1;
        this.addUnitEdit.buildId = '';
        this.addUnitEdit.unitName = '';
        this.addUnitEdit.unitList = [];
      },
      /**
       * 初始化 添加住宅列表
       */
      initHouseEdit() {
        this.addHouseEdit.show = false;
        this.addHouseEdit.buildId = '';
        this.addHouseEdit.unitId = '';
        this.addHouseEdit.unitList = [];
        this.addHouseEdit.beginFloor = '';
        this.addHouseEdit.endFloor = '';
        this.addHouseEdit.beginHouseNum = '';
        this.addHouseEdit.endHouseNum = '';
      },
      /**
       * 下一步
       */
      addBuildNextStep1Click() {
        this.$validate(true, () => {
        });
        if (!this.$v1.buildnum.valid) {
          message.error("请填写完整与正确");
          return;
        }
        apiSource({
          type: 'outer',
          service: 'communityBuildingAdd',
          ct: {
            "villageId": this.villageId,
            "buildingNames": [this.addBuildEdit.buildNum]
          }
        }).then((res) => {
          if (!isEmptyObject(res)) {
            this.$resetValidation();
            this.addBuildEdit.buildId = res[0].buildingId;
            this.addBuildEdit.step = 2;
            console.debug("添加楼宇成功");
            message.success("添加楼宇成功");
            this.afterAddBuild();
          } else {
            message.error("该楼宇已存在");
          }

        }, (e) => {
          message.error("添加楼宇失败");
          console.log("添加楼宇失败：");
          console.log(e);
        });
      },
      /**
       * 下一步（2）
       */
      addBuildNextStep2Click() {
        this.$validate(true, () => {
        });
        if (!this.$v1.unitnum.valid) {
          message.error("请填写完整与正确");
          return;
        }
        var unitNumList = [];
        for (let i = 1; i <= this.addBuildEdit.unitCount; i++) {
          unitNumList.push(i);
        }
        apiSource({
          type: 'outer',
          service: 'communityUnitAdd',
          ct: {
            "buildingIds": [this.addBuildEdit.buildId],
            "unitNames": unitNumList
          }
        }).then((res) => {
          message.success("批量添加单元成功");
          console.debug("批量添加单元成功");
          this.addBuildEdit.unitList = [];
          for (let i = 0; i < res.length; i++) {
//            this.addBuildEdit.unitList.$set(i,unitList[i].unitId);
            var unit = {
              unitId: res[i].unitId,
              unitName: res[i].unitName,
              unitName: res[i].unitName,
              beginFloor: '',
              endFloor: '',
              beginHouseNum: '',
              endHouseNum: ''
            };
            this.addBuildEdit.unitList.push(unit)
          }
          console.log(this.addBuildEdit);
          this.addBuildEdit.step = 3;
          this.afterAddUnit();
        }, (e) => {
          message.error("批量添加单元失败");
          console.log("批量添加单元失败：");
          console.log(e);
        });
      },
      /**
       * 保存
       */
      addBuildOkClick() {
        this.$validate(true, () => {
        });
        if (!this.$v1.valid) {
          message.error("请填写完整与正确");
          return;
        }
        console.debug("准备批量添加住宅");
        console.debug(this.addBuildEdit);
        let taskPromiseList = [];
        for (let i = 0; i < this.addBuildEdit.unitList.length; i++) {
          var promise = this.addUnit(this.addBuildEdit.unitList[i].unitId, this.addBuildEdit.unitList[i].beginHouseNum, this.addBuildEdit.unitList[i].endHouseNum, this.addBuildEdit.unitList[i].beginFloor, this.addBuildEdit.unitList[i].endFloor);
          taskPromiseList.push(promise);
        }
        Promise.all(taskPromiseList).then((resList) => {
          message.success("批量添加住宅成功");
          console.debug("批量添加住宅成功");
          console.debug(resList);
          this.hideAddBuildModal();
          this.afterAddHouse();
        }).catch((e) => {
          //其中有执行添加失败的
          console.log(e);
          this.hideAddBuildModal();
          this.afterAddHouse();
        })

      },
      /**
       * 下一步
       */
      addUnitNextStep1Click() {
        this.$validate(true, () => {
        });
        if (!(this.$v2.buildid.valid && this.$v2.unitnum.valid)) {
          message.error("请填写完整与正确");
          return;
        }
        console.debug("准备添加单元：");
        console.debug(this.addUnitEdit);
        apiSource({
          type: 'outer',
          service: 'communityUnitAdd',
          ct: {
            "buildingIds": [this.addUnitEdit.buildId],
            "unitNames": [this.addUnitEdit.unitName]
          }
        }).then((res) => {
          this.addBuildEdit.unitList = [];
          if (isEmptyObject(res)) {
            //该单元已存在
            message.error("该单元已存在");
          } else {
            //该单元不存在
            let unit = {
              unitId: res[0].unitId,
              unitName: res[0].unitName,
              unitName: res[0].unitName,
              beginFloor: '',
              endFloor: '',
              beginHouseNum: '',
              endHouseNum: ''
            };
            this.addUnitEdit.unitList.push(unit);
            console.debug(this.addUnitEdit);
            this.addUnitEdit.step = 2;
            this.afterAddUnit();
          }
        }, (e) => {
          message.error("添加单元失败");
          console.log("添加单元失败：");
          console.log(e);
        });
      },
      /**
       * 保存
       */
      addUnitOkClick() {
        this.$validate(true, () => {
        });
        if (!this.$v2.valid) {
          message.error("请填写完整与正确");
          return;
        }
        console.debug("准备批量添加住宅");
        console.debug(this.addUnitEdit);
        this.addUnit(this.addUnitEdit.unitList[0].unitId, this.addUnitEdit.unitList[0].beginHouseNum, this.addUnitEdit.unitList[0].endHouseNum, this.addUnitEdit.unitList[0].beginFloor, this.addUnitEdit.unitList[0].endFloor).then((res) => {
          message.success("添加成功");
          this.hideAddUnitModal();
          this.afterAddHouse();
        }).catch((e) => {
          //执行失败
          console.log(e);
          this.hideAddUnitModal();
        });
      },
      /**
       * 保存
       */
      addHouseOkClick() {
        this.$validate(true, () => {
        });
        if (!this.$v3.valid) {
          message.error("请填写完整与正确");
          return;
        }
        console.debug("现在的addHouseEdit:");
        console.debug(this.addHouseEdit);
        apiSource({
          type: 'outer',
          service: 'communityHouseAdd',
          ct: {
            "unitIds": [this.addHouseEdit.unitId],
            "beginHouseNum": this.addHouseEdit.beginHouseNum,
            "endHouseNum": this.addHouseEdit.endHouseNum,
            "beginFloor": this.addHouseEdit.beginFloor,
            "endFloor": this.addHouseEdit.endFloor
          }
        }).then((res) => {
          message.success("添加住宅成功");
          console.debug("添加住宅成功：");
          console.debug(res);
          this.hideAddHouseModal();
          this.afterAddHouse();
        }, (e) => {
          message.error(e.msg);
          console.log("添加住宅失败", e);
        });
      },

      goAddBuildStep(step) {
        this.addBuildEdit.step = step;
      },
      /**
       * 获取住宅列表
       * @param {String} villageId 小区ID
       */
      getBuildingList(villageId) {
        if (!villageId) {
          return;
        }
        apiSource({
          type: 'outer',
          service: 'communityBuildingList',
          ct: {
            "pageFirst": 1,
            "pageSize": 100,
            "villageId": villageId,
          }
        }).then((res) => {
          console.debug(res);
          if (!isEmptyObject(res.recordList)) {
            this.buildList = res.recordList;
          } else {
            this.buildList = [];
            this.loadMoreTxt = "没有更多数据了";
          }
        });
      },
      /**
       * 选中楼栋
       */
      addHouseBuildChange() {
        console.debug(this.addHouseEdit);
        this.addHouseEdit.unitList = [];
        apiSource({
          type: 'outer',
          service: 'communityUnitList',
          ct: {
            "buildingId": this.addHouseEdit.buildId,
            "pageFirst": 1,
            "pageSize": 50
          }
        }).then((res) => {
          console.debug("选择了其他楼栋：");
          console.debug(res);
          for (let i = 0, l = res.recordList.length; i < l; i++) {
            this.addHouseEdit.unitList.push(res.recordList[i]);
          }
        });

      },
      /**
       * 准备批量添加住宅
       * @param {String} unitId         楼道ID
       * @param {String} beginHouseNum  开始房号
       * @param {String} endHouseNum    结束房号
       * @param {String} beginFloor     开始楼层
       * @param {String} endFloor       结束楼层
       * @returns {Promise}
       */
      addUnit(unitId, beginHouseNum, endHouseNum, beginFloor, endFloor) {
        return new Promise((resolve, reject) => {
          apiSource({
            type: 'outer',
            service: 'communityHouseAdd',
            ct: {
              "unitIds": [unitId],
              "beginHouseNum": beginHouseNum,
              "endHouseNum": endHouseNum,
              "beginFloor": beginFloor,
              "endFloor": endFloor
            }
          }).then((res) => {
            console.debug("添加住宅成功");
            console.debug(res);
            resolve(res);
          }, (e) => {
            message.error("添加住宅失败");
            console.log("添加住宅失败：");
            console.log(e);
            reject(e);
          });
        })
      }
    }
  }
</script>

<style lang="less" scoped>
  @import "../../assets/less/pages.less";

  .table > thead > tr > th:last-child, .table > tbody > tr > td:last-child {
    text-align: left;
  }

  .clear-td-first {
    color: #333333 !important;
    font-size: 12px !important;
  }

  .step-module {
    margin-top: 20px;
    background-color: #fff;
  }

  .steps li {
    font-size: 13px;
  }

  .unit-name {
    width: 100px;
  }

  .unit-name-input {
    width: 40px;
  }

  .num-group {
    width: 135px;
  }

  .begin-end {
    width: 10px;
    text-align: center;
  }

  .num-input {
    width: 40px;
  }

  .invalid.touched {
    border: 1px solid red;
  }
</style>
